<template>
  <div class="search-tree-container">
    <div class="search-bar">
      <a-input
          v-model:value="searchValue"
          placeholder="搜索设备..."
          @keyup.enter="handleSearch"
      >
        <template #prefix-icon>
          <Icon type="search" />
        </template>
      </a-input>

      <a-button type="primary" @click="handleSearch" style="margin-left: 8px">
        搜索
      </a-button>
      <a-button @click="resetSearch" style="margin-left: 8px">
        重置
      </a-button>
    </div>
    <div class="tree-container">
      <a-tree
          :data-source="filteredData"
          :expanded-keys="expandedKeys"
          :selected-keys="selectedKeys"
          :default-expand-all="defaultExpandAll"
          @select="handleSelect"
          @expand="handleExpand"
      />
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, watch } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { Icon, Tree, Button, Input } from '@arco-design/web-vue';
import { getDeviceList } from './api';

// 响应式数据
const searchValue = ref('');
const deviceList = ref([]);
const filteredData = ref([]);
const expandedKeys = ref([]);
const selectedKeys = ref([]);
const defaultExpandAll = ref(false);
const route = useRoute();
const router = useRouter();

// 初始化获取设备列表
onMounted(async () => {
  try {
    const data = await getDeviceList();
    deviceList.value = transformDeviceData(data);
    filteredData.value = deviceList.value;
    // 展开第一级节点
    if (deviceList.value.length > 0) {
      expandedKeys.value = [deviceList.value[0].key];
    }
  } catch (error) {
    console.error('获取设备列表失败', error);
  }
});

// 搜索处理
const handleSearch = () => {
  if (!searchValue.value) {
    filteredData.value = deviceList.value;
    return;
  }

  // 过滤设备列表
  filteredData.value = deviceList.value.filter(item => {
    return item.title.includes(searchValue.value) ||
        (item.children && item.children.some(child =>
            child.title.includes(searchValue.value)));
  });
};

// 重置搜索
const resetSearch = () => {
  searchValue.value = '';
  filteredData.value = deviceList.value;
};

// 树节点选择处理
const handleSelect = (keys) => {
  selectedKeys.value = keys;
  // 获取选中的设备ID并触发事件
  const selectedDevice = findDeviceByKey(keys[0]);
  if (selectedDevice) {
    emit('device-select', selectedDevice.deviceSn);
  }
};

// 树节点展开处理
const handleExpand = (expandedKeys) => {
  expandedKeys.value = expandedKeys;
};

// 根据key查找设备
const findDeviceByKey = (key) => {
  if (!key) return null;

  const findInChildren = (children, targetKey) => {
    for (const child of children) {
      if (child.key === targetKey) {
        return child;
      }
      if (child.children && child.children.length > 0) {
        const result = findInChildren(child.children, targetKey);
        if (result) return result;
      }
    }
    return null;
  };

  return findInChildren(deviceList.value, key);
};

// 转换设备数据为树结构
const transformDeviceData = (data) => {
  return data.map(item => {
    return {
      key: item.id.toString(),
      title: item.deviceName,
      children: item.children ? item.children.map(child => ({
        key: child.id.toString(),
        title: child.deviceName,
        deviceSn: child.deviceSn,
        children: [] // 这里简化处理，实际可能有更深层级
      })) : []
    };
  });
};

// 定义组件事件
const emit = defineEmits(['device-select']);
</script>

<style scoped>
.search-tree-container {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.search-bar {
  padding: 12px;
  background-color: #f5f7fa;
  border-bottom: 1px solid #e5e9f2;
  display: flex;
  align-items: center;
}

.tree-container {
  flex: 1;
  overflow-y: auto;
  padding: 8px;
}
</style>